package com.qzyh.esb.egsa.interceptor;


import com.qzyh.esb.egsa.config.JwtConfig;
import com.qzyh.esb.egsa.utils.BaseContextUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    //通过LogFactory获取Logger类的实例
    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private JwtConfig jwtConfig ;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        /** Token 验证 */
        String token = request.getHeader(jwtConfig.getHeader());

        Claims claims = null;
        try{
            claims = jwtConfig.getTokenClaim(token);
            if(claims == null || jwtConfig.isTokenExpired(claims.getExpiration())){
                throw new JwtException(jwtConfig.getHeader() + "失效，请重新登录。");
            }
        }catch (Exception e){
            throw new JwtException(jwtConfig.getHeader() + "失效，请重新登录。");
        }
        /** 将用户身份ID存入上下文工具 */
        BaseContextUtil.setUserId(claims.getSubject());
        return true;
    }
}
